/**
 * @author: 最帅的的乐乐
 * @date: 2025-02-17 13:36 星期一
 * @motto the harder, the luckier。
 */

public class _35_SearchInsert {
    public static int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            // 计算中间元素的索引
            int mid = (left + right) >>> 1;  // 使用无符号右移，避免溢出

            // 检查目标值是否在中间位置
            if (nums[mid] == target) {
                return mid; // 找到目标，返回索引
            } else if (nums[mid] < target) {
                left = mid + 1; // 目标在右边
            } else {
                right = mid - 1; // 目标在左边
            }
        }

        return left; // 目标不在数组中，返回 -1
    }

    public static void main(String[] args) {
        int[] nums = {1,3,5,6};
        int target = 2;

        int lastIndex = searchInsert(nums, target);

        if (lastIndex != -1) {
            System.out.println("The last occurrence of " + target + " is at index: " + lastIndex);
        } else {
            System.out.println("The target value " + target + " is not found.");
        }
    }
}
